self.onmessage = async e => {
  if (e.data.type === 'init') {
    const {videoUrl, totalFrames, interval} = e.data
    const frameMap = new Map()

    try {
      const response = await fetch(videoUrl)
      const videoBlob = await response.blob()
      const video = await createVideoElementFromBlob(videoBlob)

      for (let i = 0; i < totalFrames; i++) {
        const time = i * interval
        video.currentTime = time
        await new Promise(resolve => {
          const onSeeked = () => {
            video.removeEventListener('seeked', onSeeked)
            resolve()
          }
          video.addEventListener('seeked', onSeeked)
        })

        const bitmap = await createImageBitmap(video)
        frameMap.set(i, bitmap)
      }

      self.postMessage({type: 'framesReady', frameMap})
    } catch (error) {
      console.error('Worker出错:', error)
    }
  }
}

function createVideoElementFromBlob(blob) {
  return new Promise(resolve => {
    const video = document.createElement('video')
    video.src = URL.createObjectURL(blob)
    video.muted = true
    video.playsInline = true
    video.addEventListener('loadedmetadata', () => resolve(video), {once: true})
    video.load()
  })
}
